package cs575.fantasyclient.services;

import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import cs575.common.ConnectionThread;
import cs575.common.FantasyMessage;
import cs575.common.OpCodes;
import cs575.common.Player;
import cs575.fantasyclient.client.ClientParser;


public class GetAllPlayers {
	public void execute(String ip, int port) {
		FantasyMessage message = new FantasyMessage();
		message.setOpCode(OpCodes.GET_ALL_PLAYERS);
		message.setMessage(new byte[0]);
		
		try {
			Socket socket = new Socket(ip, port);
			socket.getOutputStream().write(message.toBytes());
			
			ConnectionThread ct = new ConnectionThread(socket, new ClientParser());
			ct.start();
		} catch (IOException e) {
			System.err.println("Connection Refused");
		}
	}
	
	public List<Player> execute(FantasyMessage message){
		List<Player> retList = new ArrayList<Player>();
		
		ByteBuffer playBuffer = ByteBuffer.wrap(message.getMessage());
		int numOfPlayers = playBuffer.getInt();
		for (int i = 0 ; i < numOfPlayers ; i++){
			int size = playBuffer.getInt();
			byte [] player = new byte[size];
			playBuffer.get(player);
			Player newPlayer = new Player(player);
			retList.add(newPlayer);
		}
		
		return retList;
	}
}
